﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 约苗秒杀.Models;
using 约苗秒杀.Service;

namespace 约苗秒杀.Service
{
    public class HttpService
    {

        private string baseUrl = "https://miaomiao.scmttec.com";

        Form1 form;
        public HttpService(Form1 form)
        {
            this.form = form;
        }

        /***
         * 获取秒杀资格
         * @param seckillId 疫苗ID
         * @param vaccineIndex 固定1
         * @param linkmanId 接种人ID
         * @param idCard 接种人身份证号码
         * @return 返回订单ID
         * @throws IOException
         * @throws BusinessException
         */
        public string secKill(string seckillId, string vaccineIndex, string linkmanId, string idCard)
        {
            string path = baseUrl + "/seckill/seckill/subscribe.do";
            Dictionary<string, string> _params = new Dictionary<string, string>();
            _params.Add("seckillId", seckillId);
            _params.Add("vaccineIndex", vaccineIndex);
            _params.Add("linkmanId", linkmanId);
            _params.Add("idCardNo", idCard);
            //后面替换成接口返回的st
            //目前发现接口返回的st就是当前时间，后面可能会固定为一个加密参数
            long st = (long)(DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0)).TotalMilliseconds;

            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("ecc-hs", eccHs(seckillId, st));
            return Get(path, _params, header);
        }

        /**
         * 获取疫苗列表
         * @return
         * @throws BusinessException
         */
        public List<VaccineList> getVaccineList(string regionCode = null)
        {
            hasAvailableConfig();
            string path = baseUrl + "/seckill/seckill/list.do";
            Dictionary<string, string> param = new Dictionary<string, string>();
            //九价疫苗的code
            param.Add("offset", "0");
            param.Add("limit", "100");
            //这个应该是成都的行政区划前四位
            param.Add("regionCode", regionCode ?? Config.regionCode);
            string json = Get(path, param, null);
            return JsonConvert.DeserializeObject<List<VaccineList>>(json);
        }


        /**
         * 获取接种人信息
         * @return
         */
        public List<Member> getMembers()
        {
            string path = baseUrl + "/seckill/linkman/findByUserId.do";
            string json = Get(path, null, null);
            return JsonConvert.DeserializeObject<List<Member>>(json);
            // return JSONObject.parseArray(json, Member.class);
        }
        /***
         * 获取加密参数st
         * @param vaccineId 疫苗ID
         */
        public string getSt(string vaccineId)
        {
            string path = baseUrl + "/seckill/seckill/checkstock2.do";
            Dictionary<string, string> _params = new Dictionary<string, string>();
            _params.Add("id", vaccineId);
            string json = Get(path, _params, null);
            var jsonObject = JsonConvert.DeserializeObject<JObject>(json);
            return jsonObject["data"]["st"].ToString();
        }

        private void hasAvailableConfig()
        {
            if (string.IsNullOrEmpty(Config.cookies))
            {
                form.SendMeg("请先配置cookie");
            }
        }

        private string Get(string path, Dictionary<string, string> _params, Dictionary<string, string> extHeader)
        {
            if (_params != null && _params.Count != 0)
            {
                StringBuilder paramStr = new StringBuilder("?");
                foreach (var item in _params)
                {
                    paramStr.Append(item.Key).Append("=").Append(item.Value).Append("&");
                }
                string t = paramStr.ToString();
                if (t.EndsWith("&"))
                {
                    t = t.Substring(0, t.Length - 1);
                }
                path += t;
            }
            HttpExtend http = new HttpExtend();
            if (extHeader == null) extHeader = new Dictionary<string, string>();
            foreach (var item in getCommonHeader())
            {
                extHeader.Add(item.Key, item.Value);
            }
            string json = HttpHelper.HttpGet(path, null, extHeader); //http.Get<string, string>(path, null, extHeader).Result;
            JObject jsonObject = JsonConvert.DeserializeObject<JObject>(json);
            if (jsonObject["code"].ToString() == "0000")
            {
                return jsonObject["data"].ToString();
            }
            else
            {
                form.SendMeg(jsonObject["code"].ToString() + "--" + jsonObject["msg"].ToString());
                return "";
            }
        }

        private Dictionary<string, string> getCommonHeader()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            //headers.Add("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; SM-N960F Build/JLS36C; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 MMWEBID/1042 MicroMessenger/7.0.15.1680(0x27000F34) Process/appbrand0 WeChat/arm32 NetType/WIFI Language/zh_CN ABI/arm32");
            headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
            headers.Add("Referer", "https://servicewechat.com/wxff8cad2e9bf18719/2/page-frame.html");
            headers.Add("tk", Config.tk);
            headers.Add("Accept", "application/json, text/plain, */*");
            headers.Add("Host", "miaomiao.scmttec.com");
            headers.Add("Cookie", Config.cookies);
            return headers;
        }

        private string eccHs(string seckillId, long st)
        {
            string salt = "ux$ad70*b";
            int memberId = Config.memberId;
            string md5 = (seckillId + st + memberId).GetMD5();
            return (md5 + salt).GetMD5();
        }





        /***
         * 获取接种日期
         * @param vaccineId 疫苗ID
         * @param orderId 订单ID
         */
        public List<SubDate> getSkSubDays(string vaccineId, string orderId)
        {
            string path = baseUrl + "/seckill/seckill/subscribeDays.do";
            Dictionary<string, string> _params = new Dictionary<string, string>();
            _params.Add("id", vaccineId);
            _params.Add("sid", orderId);
            string json = Get(path, _params, null);
            //logger.info("日期格式:{}", json);
            return JsonConvert.DeserializeObject<List<SubDate>>(json);
            //return JSONObject.parseArray(json).toJavaList(SubDate.class);
        }

        /**
         * 根据接种日期，获取接种时间段
         * @param vaccineId
         * @param orderId
         * @param day 接种日期 YYYY-MM-DD
         * @return
         * @throws IOException
         * @throws BusinessException
         */
        public List<SubDateTime> getSkSubDayTime(string vaccineId, string orderId, string day)
        {
            string path = baseUrl + "/seckill/seckill/dayTimes.do";
            Dictionary<string, string> _params = new Dictionary<string, string>();
            _params.Add("id", vaccineId);
            _params.Add("sid", orderId);
            _params.Add("day", day);
            string json = Get(path, _params, null);
            //System.out.println("根据选择的日期，获取的时间格式" + json);
            return JsonConvert.DeserializeObject<List<SubDateTime>>(json);

            ///return JSONObject.parseArray(json).toJavaList(SubDateTime.class);
        }

        /**
         * 提交接种时间
         * @param vaccineId
         * @param orderId
         * @param day 接种日期 YYYY-MM-DD
         * @return
         * @throws IOException
         * @throws BusinessException
         */
        public void subDayTime(string vaccineId, string orderId, string day, string wid)
        {
            string path = baseUrl + "/seckill/seckill/submitDateTime.do";
            Dictionary<string, string> _params = new Dictionary<string, string>();
            _params.Add("id", vaccineId);
            _params.Add("sid", orderId);
            _params.Add("day", day);
            _params.Add("wid", wid);
            string json = Get(path, _params, null);
            //  logger.info("提交接种时间，返回数据: {}", json);
        }
    }

}
